<template>
  <el-dialog title="下发人脸" v-model="visible" :close-on-click-modal="false" :close-on-press-escape="false" width="801px">
    <el-steps :active="stepActive" simple style="margin-bottom: 20px; transform: scale(0.9)">
      <el-step title="选择设备" icon="el-icon-video-camera"></el-step>
      <el-step title="选择用户" icon="el-icon-picture-outline"></el-step>
      <el-step title="确认下发" icon="el-icon-download"></el-step>
    </el-steps>
    <el-form ref="dataFormRef" :model="dataForm" label-position="right" label-width="120px" style="position: relation">
      <div v-show="stepActive === 0" style="margin: 0 60px">
        <el-tree :data="deviceList" ref="deviceTree" node-key="id" default-expand-all highlight-current show-checkbox
          @check-change="handleSelectDevice()"
          :style="{ height: 316 + 'px', overflowY: 'scroll', marginRight: '10px' }">
          <template v-slot="scope">
            <span class="custom-tree-node">
              <span>{{ scope.data.deviceName }}</span>
              <span>{{ scope.data.deviceCode ? '-' : '' }}{{ scope.data.deviceCode }}</span>
            </span>
          </template>
        </el-tree>
      </div>
      <div v-show="stepActive === 1">
        <div class="transfer-box" :style="{ height: 368 + 'px' }">
          <div class="transfer-box-item">
            <el-tree :data="tree" ref="deptTree" style="margin-top: 10px"
              :style="{ height: 320 + 'px', overflowY: 'scroll' }" @expand-change="expandChange" node-key="id"
              :expand-on-click-node="false" accordion show-checkbox :check-strictly="true" @check-change="handleSelect">
              <template v-slot="scope">
                <span class="custom-tree-node">
                  <span>{{ scope.data.name }}</span>
                </span>
              </template>
            </el-tree>
          </div>
          <div class="transfer-box-btn">
            <el-button type="primary" @click="getUserList" :disabled="!selectedItem.id" :icon="ArrowLeft"
              :loading="fetchUserLoading">获取</el-button>
            <el-button type="danger" @click="removeUser" :disabled="!checkedUserIds.length"
              :icon="ArrowRight">删除</el-button>
          </div>
          <div class="transfer-box-item" v-loading="fetchUserLoading" element-loading-text="正在获取用户..."
            element-loading-spinner="el-icon-loading" element-loading-background="rgba(255, 255, 255, 0.6)">
            <div class="transfer-box-item-header">
              <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange"
                style="margin: 0">全选</el-checkbox>
              <el-checkbox :indeterminate="isIndeterminate" v-model="checkMan" @change="handleCheckManChange"
                style="margin: 0">男</el-checkbox>
              <el-checkbox :indeterminate="isIndeterminate" v-model="checkWoman" @change="handleCheckWomanChange"
                style="margin: 0">女</el-checkbox>
              <span class="count">{{ checkedUserIds.length }}/{{ userList.length }}</span>
            </div>
            <div class="check-user-box">
              <el-checkbox-group v-model="checkedUserIds" @change="handleCheckedChange">
                <el-checkbox v-for="(item, index) in userList" :label="item.id" :key="index" style="display: block">{{
    item.name }}</el-checkbox>
              </el-checkbox-group>
            </div>
          </div>
        </div>
      </div>
      <div v-show="stepActive === 2">
        <el-form-item label="已选设备">
          <el-select v-model="deviceNameList" multiple collapse-tags style="margin-left: 20px; width: 90%"
            placeholder="请选择">
            <el-option v-for="item in deviceNameList" :key="item.value" :label="item" :value="item" disabled>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="已选用户">
          <el-table :data="checkedUserList" :height="288" highlight-current-row center ref="multipleTableRef"
            size="mini" style="width: 90%">
            <el-table-column prop="name" label="姓名" align="center" sortable></el-table-column>
            <el-table-column prop="typeName" label="用户类型" align="center">
              <template v-slot="scope">
                {{ PersonTypeMap[scope.row.personType] || '学生' }}
              </template>
            </el-table-column>
            <el-table-column prop="className" label="所属部门" align="center"></el-table-column>
            <el-table-column prop="imageUrl" label="人脸照片" align="center">
              <template v-slot="scope">
                <el-image :src="scope.row.imageUrl" fit="cover" style="width: 60px;height: 60px;"
                  v-if="scope.row.imageUrl"></el-image>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </div>
    </el-form>
    <template v-slot:footer>
      <el-button @click="visible = false">{{ $t("cancel") }}</el-button>
      <el-button v-if="stepActive !== 0" @click="preStep">上一步</el-button>
      <el-button type="primary" @click="nextStep" :loading="loading" v-if="stepActive !== 2">下一步</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="loading" v-else>确定下发</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import baseService from '@/service/baseService';
import { ElMessage } from 'element-plus';
import { reactive, ref, watch } from 'vue';
import {
  ArrowLeft,
  ArrowRight,
} from '@element-plus/icons-vue'
import { GenderMap, PersonTypeMap } from './contant';

const emit = defineEmits(["refreshDataList"]);

const visible = ref(false);
const loading = ref(false);
const fetchUserLoading = ref(false);
const deviceLoading = ref(false);
const fetchDeptLoading = ref(false);
const dataForm = ref<any>({});
const deviceNameList = ref<any[]>([]);
const deviceInfoIdsList = ref<any[]>([]);
const deviceList = ref<any[]>([{ deviceName: '全选', id: 0, children: [], isHead: true }]);
const tree = ref<any[]>([]);
const type = ref(1);
const stepActive = ref(0);
const checkedUserIds = ref<any[]>([]);
const userList = ref<any[]>([]);
const checkedUserList = ref<any[]>([]);
const isIndeterminate = ref(false);
const checkAll = ref(false);
const checkMan = ref(false);
const checkWoman = ref(false);
const selectedItem = ref<any>({});
const username = ref("");

const deptTree = ref();
const deviceTree = ref();
const multipleTableRef = ref();
const dataFormRef = ref();

const init = () => {
  visible.value = true;
  loading.value = false;
  stepActive.value = 0;
  userList.value = [];
  checkedUserList.value = [];
  checkedUserIds.value = [];

  // 重置表单数据
  if (dataFormRef.value) {
    dataFormRef.value.resetFields();
  }

  getDeptList();
  getDeviceList();
};

const removeUser = () => {
  userList.value = userList.value.filter((item: any) => !checkedUserIds.value.some(ele => ele === item.userId))
  checkedUserList.value = []
  checkedUserIds.value = []
};
const handleCheckAllChange = (val: any) => {
  checkMan.value = false
  checkWoman.value = false
  var userIds = Array.from(userList.value, ({ id }) => id)
  checkedUserList.value = val ? userList.value : []
  checkedUserIds.value = val ? userIds : []
  isIndeterminate.value = false
};
const handleCheckManChange = (val: any) => {
  checkAll.value = false
  checkWoman.value = false
  const list: any[] = [];
  userList.value.map((v: { gender: number; }) => {
    if (v.gender === 1) {
      list.push(v)
    }
  })
  var userIds: any[] = Array.from(list, ({ id }) => id);
  checkedUserList.value = val ? list : []
  checkedUserIds.value = val ? userIds : []
  isIndeterminate.value = false
};
const handleCheckWomanChange = (val: any) => {
  checkMan.value = false
  checkAll.value = false
  const list: any[] = [];
  userList.value.map((v: { gender: number; }) => {
    if (v.gender === 0) {
      list.push(v)
    }
  })
  var userIds: any = Array.from(list, ({ id }) => id)
  checkedUserList.value = val ? list : []
  checkedUserIds.value = val ? userIds : []
  isIndeterminate.value = false
};
const handleCheckedChange = (value: any[]) => {
  checkedUserList.value = userList.value.filter((item: { userId: any; }) => value.some((ele: any) => ele === item.userId))
  let checkedCount = value.length
  checkAll.value = checkedCount === userList.value.length
  isIndeterminate.value = checkedCount > 0 && checkedCount < userList.value.length
};

const fetchUserList = async (params: any) => {
  return new Promise((resolve, reject) => {
    baseService.get("/data/personnel/student/page", { ...params }).then((res: { data: { list: any[]; }; }) => {
      resolve(res.data.list)
    }).catch(() => {
      reject([]);
    });
  })
}
const getUserList = async () => {
  var params = {}
  let list: any[] = [];
  fetchUserLoading.value = true
  if (type.value === 1 || type.value === 2) {
    params = {
      page: 1,
      limit: 10000,
      classId: selectedItem.value.id,
    }
    list = (await fetchUserList(params)) as any[];
  } else {
    params = {
      page: 1,
      limit: 15,
      username: username.value,
    }
    list = (await fetchUserList(params)) as any[];
  }

  fetchUserLoading.value = false
  userList.value.push(...list);
  var obj: any = {}
  userList.value = userList.value.reduce(function (item: any[], next: { id: string | number; }) {
    obj[next.id] ? '' : (obj[next.id] = true && item.push(next))
    return item
  }, [])

  var userIds = Array.from(userList.value, ({ id }) => id)
  checkedUserList.value = userList.value;
  checkedUserIds.value = userIds
  isIndeterminate.value = false
  checkAll.value = true
  deptTree.value.setCheckedKeys([])
  selectedItem.value.disabled = true;
  selectedItem.value.id = '';
  username.value = '';
};
const preStep = () => {
  stepActive.value--;
  deviceTree.value.setCheckedKeys(deviceInfoIdsList)
};
const nextStep = () => {
  if (stepActive.value === 0) {
    if (deviceNameList.value.length === 0) {
      ElMessage.error('请选择设备');
      return
    }
    stepActive.value++
  } else if (stepActive.value === 1) {
    if (checkedUserList.value.length === 0) {
      ElMessage.error('请选择用户')
      return
    }
    stepActive.value++;
    dataForm.value.issAuthInfos = [];
    checkedUserList.value = checkedUserList.value.filter((k) => k.imageUrl);
    checkedUserList.value.map((v: any) => {
      const obj = {
        classId: v.classId,
        faceId: v.faceId,
        gender: v.gender,
        idNumber: v.idNumber,
        imagePath: v.imagePath,
        imageUrl: v.imageUrl,
        name: v.name,
        personType: v.personType,
      };
      dataForm.value.issAuthInfos.push(obj);
    })
  }
};

const handleSelectDevice = () => {
  let res = []
  res = deviceTree.value.getCheckedNodes()
  dataForm.value.deviceIds = []
  deviceNameList.value = []
  deviceInfoIdsList.value = []
  res.map((v: any) => {
    if (!v.isHead) {
      dataForm.value.deviceIds.push(v.id)
      deviceNameList.value.push(v.deviceName)
      deviceInfoIdsList.value.push(v.id)
    }
  })
  deviceNameList.value.toString();
  console.log(dataForm.value);
};

const getDeviceList = () => {
  deviceLoading.value = true;
  baseService.get("/device/info/page", {
    page: 1,
    limit: 500
  }).then((res: { data: { list: any[]; }; }) => {
    deviceLoading.value = false;
    console.log(res.data.list);
    deviceList.value[0].children = res.data.list;
    console.log('deviceList', deviceList.value);
  });
};

const getDeptList = () => {
  fetchDeptLoading.value = true;
  baseService.get("/data/class/list").then((res) => {
    fetchDeptLoading.value = false;
    if (res.code !== 0) {
      return ElMessage.error(res.msg);
    }
    tree.value = res.data;
  });
};

const handleSubmit: any = () => {
  dataFormRef.value.validate((valid: boolean) => {
    if (!valid) {
      return false;
    }

    loading.value = true;
    baseService.post(`/device/auth/issBatch`, dataForm.value).then((res: any) => {
      ElMessage.success({
        message: '操作成功',
        duration: 500,
        onClose: () => {
          visible.value = false;
          emit("refreshDataList");
        }
      });
    });
  })
};
//输入姓名获取
const handleInput = () => {
  if (username) {
    selectedItem.value = { id: 1 }
  } else {
    selectedItem.value = {}
  }
};
// 选择人脸
const handleSelect = (data: any, checked: any, indeterminate: any) => {
  if (checked) {
    console.log('checked', data.id, checked);
    deptTree.value.setCheckedKeys([data.id]);
    selectedItem.value = data
  }
};
// 折叠面板每次只能展开一行
const expands = ref<any[]>([]);
const expandChange = (row: { deptId: any; id: any; }, expandedRows: string | any[]) => {
  if (expandedRows.length) {
    expands.value = []
    if (row) {
      expands.value.push(row.deptId || row.id) // 每次push进去的是每行的ID
    }
  } else {
    expands.value = [] // 默认不展开
  }
};

defineExpose({
  init
});
</script>
<style lang="scss">
.transfer-box {
  display: flex;
  margin: 0 20px;
  padding: 10px;

  &-item {
    // height: 400px;
    // flex: 1;
    // border: 1px solid rgb(231, 229, 229);
    // padding: 20px 0;
    // box-sizing: border-box;
    border: 1px solid #ebeef5;
    border-radius: 4px;
    overflow: hidden;
    background: #fff;
    display: inline-block;
    vertical-align: middle;
    width: 240px;
    max-height: 100%;
    box-sizing: border-box;

    &-header {
      height: 40px;
      line-height: 40px;
      background: #f5f7fa;
      margin: 0;
      padding: 0 15px;
      border-bottom: 1px solid #ebeef5;
      box-sizing: border-box;
      color: #000;
      display: flex;
      justify-content: space-between;

      .count {
        color: #909399;
        font-size: 12px;
        font-weight: 400;
      }
    }
  }

  .check-user-box {
    height: 300px;
    overflow-x: scroll;
    padding-left: 15px;
    padding-top: 10px;
  }

  &-btn {
    display: flex;
    align-items: center;
    margin: 0 20px;
  }
}
</style>